package com.foftact.stockpe;

import com.foftact.stockpe.service.StockPEService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 股票财务分析数据控制器
 */
@Controller
@RequestMapping("/stockpe")
public class StockPEController {

    private static final Logger logger = LoggerFactory.getLogger(StockPEController.class);

    @Autowired
    private StockPEService stockPEService;

    /**
     * 跳转到股票财务分析数据列表页面
     */
    @GetMapping("/list")
    public String listPage() {
        return "stockpe/list";
    }

    /**
     * 异步获取股票财务分析数据列表
     */
    @GetMapping("/dataList")
    @ResponseBody
    public List<StockPE> getDataList() {
        logger.info("获取股票财务分析数据列表");
        return stockPEService.getAllStockPEs();
    }

    /**
     * 手动触发数据抓取
     */
    @GetMapping("/fetchData")
    @ResponseBody
    public Map<String, Object> fetchData() {
        Map<String, Object> result = new HashMap<>();
        try {
            logger.info("手动触发股票财务分析数据抓取");
            int count = stockPEService.fetchAndSaveStockPEData();
            result.put("success", true);
            result.put("message", "数据抓取成功，新增/更新数据：" + count + " 条");
        } catch (Exception e) {
            logger.error("手动触发数据抓取失败", e);
            result.put("success", false);
            result.put("message", "数据抓取失败：" + e.getMessage());
        }
        return result;
    }

    /**
     * 根据代码获取股票财务分析详情
     */
    @GetMapping("/detail/{code}")
    @ResponseBody
    public Map<String, Object> getDetail(@PathVariable("code") String code) {
        Map<String, Object> result = new HashMap<>();
        try {
            StockPE stockPE = stockPEService.getStockPEBySecurityCode(code);
            if (stockPE != null) {
                result.put("success", true);
                result.put("data", stockPE);
            } else {
                result.put("success", false);
                result.put("message", "未找到股票财务数据");
            }
        } catch (Exception e) {
            logger.error("获取股票财务详情失败：{}", code, e);
            result.put("success", false);
            result.put("message", "获取股票财务详情失败：" + e.getMessage());
        }
        return result;
    }

    /**
     * 跳转到数据统计页面
     */
    @GetMapping("/statistics")
    public String statisticsPage(Model model) {
        try {
            List<StockPE> stockPEs = stockPEService.getAllStockPEs();
            model.addAttribute("totalCount", stockPEs.size());
            
            // 计算一些统计指标
            BigDecimal avgPE = calculateAveragePE(stockPEs);
            model.addAttribute("averagePE", avgPE);
            
            BigDecimal avgROE = calculateAverageROE(stockPEs);
            model.addAttribute("averageROE", avgROE);
            
        } catch (Exception e) {
            logger.error("获取统计数据失败", e);
            model.addAttribute("totalCount", 0);
            model.addAttribute("averagePE", 0);
            model.addAttribute("averageROE", 0);
        }
        return "stockpe/statistics";
    }

    /**
     * 获取统计数据
     */
    @GetMapping("/statisticsData")
    @ResponseBody
    public Map<String, Object> getStatisticsData() {
        Map<String, Object> result = new HashMap<>();
        try {
            List<StockPE> stockPEs = stockPEService.getAllStockPEs();
            
            // 计算统计数据
            BigDecimal avgPE = calculateAveragePE(stockPEs);
            BigDecimal avgROE = calculateAverageROE(stockPEs);
            
            // PE分布统计
            Map<String, Integer> peDistribution = calculatePEDistribution(stockPEs);
            // ROE分布统计
            Map<String, Integer> roeDistribution = calculateROEDistribution(stockPEs);
            
            result.put("success", true);
            result.put("totalCount", stockPEs.size());
            result.put("averagePE", avgPE);
            result.put("averageROE", avgROE);
            result.put("peDistribution", peDistribution);
            result.put("roeDistribution", roeDistribution);
            
        } catch (Exception e) {
            logger.error("获取统计数据失败", e);
            result.put("success", false);
            result.put("message", "获取统计数据失败：" + e.getMessage());
        }
        return result;
    }

    /**
     * 计算平均市盈率
     */
    private BigDecimal calculateAveragePE(List<StockPE> stockPEs) {
        if (stockPEs == null || stockPEs.isEmpty()) {
            return BigDecimal.ZERO;
        }
        
        BigDecimal sum = BigDecimal.ZERO;
        int count = 0;
        
        for (StockPE stockPE : stockPEs) {
            if (stockPE.getPeTTM() != null && stockPE.getPeTTM().compareTo(BigDecimal.ZERO) > 0) {
                sum = sum.add(stockPE.getPeTTM());
                count++;
            }
        }
        
        return count > 0 ? sum.divide(new BigDecimal(count), 2, BigDecimal.ROUND_HALF_UP) : BigDecimal.ZERO;
    }

    /**
     * 计算平均ROE
     */
    private BigDecimal calculateAverageROE(List<StockPE> stockPEs) {
        if (stockPEs == null || stockPEs.isEmpty()) {
            return BigDecimal.ZERO;
        }
        
        BigDecimal sum = BigDecimal.ZERO;
        int count = 0;
        
        for (StockPE stockPE : stockPEs) {
            if (stockPE.getRoeTTM() != null) {
                sum = sum.add(stockPE.getRoeTTM());
                count++;
            }
        }
        
        return count > 0 ? sum.divide(new BigDecimal(count), 2, BigDecimal.ROUND_HALF_UP) : BigDecimal.ZERO;
    }

    /**
     * 计算PE分布
     */
    private Map<String, Integer> calculatePEDistribution(List<StockPE> stockPEs) {
        Map<String, Integer> distribution = new HashMap<>();
        distribution.put("< 10", 0);
        distribution.put("10-20", 0);
        distribution.put("20-30", 0);
        distribution.put("30-50", 0);
        distribution.put("50-100", 0);
        distribution.put("> 100", 0);
        distribution.put("负值", 0);
        
        if (stockPEs == null || stockPEs.isEmpty()) {
            return distribution;
        }
        
        for (StockPE stockPE : stockPEs) {
            if (stockPE.getPeTTM() == null) {
                continue;
            }
            
            BigDecimal pe = stockPE.getPeTTM();
            if (pe.compareTo(BigDecimal.ZERO) < 0) {
                distribution.put("负值", distribution.get("负值") + 1);
            } else if (pe.compareTo(new BigDecimal(10)) < 0) {
                distribution.put("< 10", distribution.get("< 10") + 1);
            } else if (pe.compareTo(new BigDecimal(20)) < 0) {
                distribution.put("10-20", distribution.get("10-20") + 1);
            } else if (pe.compareTo(new BigDecimal(30)) < 0) {
                distribution.put("20-30", distribution.get("20-30") + 1);
            } else if (pe.compareTo(new BigDecimal(50)) < 0) {
                distribution.put("30-50", distribution.get("30-50") + 1);
            } else if (pe.compareTo(new BigDecimal(100)) < 0) {
                distribution.put("50-100", distribution.get("50-100") + 1);
            } else {
                distribution.put("> 100", distribution.get("> 100") + 1);
            }
        }
        
        return distribution;
    }

    /**
     * 计算ROE分布
     */
    private Map<String, Integer> calculateROEDistribution(List<StockPE> stockPEs) {
        Map<String, Integer> distribution = new HashMap<>();
        distribution.put("< 5%", 0);
        distribution.put("5-10%", 0);
        distribution.put("10-15%", 0);
        distribution.put("15-20%", 0);
        distribution.put("20-30%", 0);
        distribution.put("> 30%", 0);
        distribution.put("负值", 0);
        
        if (stockPEs == null || stockPEs.isEmpty()) {
            return distribution;
        }
        
        for (StockPE stockPE : stockPEs) {
            if (stockPE.getRoeTTM() == null) {
                continue;
            }
            
            BigDecimal roe = stockPE.getRoeTTM();
            if (roe.compareTo(BigDecimal.ZERO) < 0) {
                distribution.put("负值", distribution.get("负值") + 1);
            } else if (roe.compareTo(new BigDecimal(5)) < 0) {
                distribution.put("< 5%", distribution.get("< 5%") + 1);
            } else if (roe.compareTo(new BigDecimal(10)) < 0) {
                distribution.put("5-10%", distribution.get("5-10%") + 1);
            } else if (roe.compareTo(new BigDecimal(15)) < 0) {
                distribution.put("10-15%", distribution.get("10-15%") + 1);
            } else if (roe.compareTo(new BigDecimal(20)) < 0) {
                distribution.put("15-20%", distribution.get("15-20%") + 1);
            } else if (roe.compareTo(new BigDecimal(30)) < 0) {
                distribution.put("20-30%", distribution.get("20-30%") + 1);
            } else {
                distribution.put("> 30%", distribution.get("> 30%") + 1);
            }
        }
        
        return distribution;
    }
}